package com.vf.cloud.server.graphics.server;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import com.vf.cloud.common.domain.Gpu;
import com.vf.cloud.common.util.GpuUtil;
import com.vf.cloud.common.vo.GpuVo;
import com.vf.cloud.server.mysql.MySQLServer;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
//@Component
//@EnableScheduling
public class Server {
	
    @Scheduled(fixedRate = 1000)
    @Async 
    public void scheduled() throws Exception {
    	List<GpuVo> list=GpuUtil.getGPUs();
    	if(list!=null) {
    		if(!MySQLServer.getInstance().isOk()) {
    			return;
    		}
    		
			List<Gpu> olds = Gpu.dao.findAll();
			Map<String, Gpu> map = new HashMap<String, Gpu>();
			for (Gpu g : olds) {
				map.put(g.getId(), g);
			}
			List<GpuVo> gpus=GpuUtil.getGPUs();
			for(GpuVo e:gpus) {
				if (!map.containsKey(e.getUuid())) {
					Gpu gpu = new Gpu();
					gpu.setId(e.getUuid());
					gpu.setName(e.getName());
					gpu.setMemoryTotal(e.getMemoryTotal());
					gpu.setBoardId(e.getBoardId());
					gpu.setVbiosVersion(e.getVbiosVersion());
					gpu.setLimit(1);
					
					gpu.setMemoryFree(e.getMemoryFree());
					gpu.setMemoryReserved(e.getMemoryReserved());
					gpu.setMemoryUsed(e.getMemoryUsed());
					
					
					gpu.save();
				} else {
					Gpu gpu = new Gpu();
					gpu.setId(e.getUuid());
					gpu.setMemoryFree(e.getMemoryFree());
					gpu.setMemoryReserved(e.getMemoryReserved());
					gpu.setMemoryUsed(e.getMemoryUsed());
					gpu.update();
					map.remove(e.getUuid());
				}
			}
			Iterator<String> it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				Gpu.dao.deleteById(key);
			}
    	}
    }
    
    public void getGPU() {
    	
    }
    

}
